<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\Http\Requests\Backend\MenuRequest;
use App\Models\Menu;
use Spatie\Permission\Models\Permission;

class MenuController extends Controller
{
    public function index(Menu $administratorMenu)
    {
        $menus = $administratorMenu->menus();
        $permissions = Permission::where('guard_name','admin')->get();

        return view('backend.menu.index', compact('menus', 'permissions'));
    }

    public function create(Menu $administratorMenu)
    {
        $permissions = Permission::get();
        $menus = $administratorMenu->menus();

        return view('backend.menu.create', compact('menus', 'permissions'));
    }

    public function store(MenuRequest $request)
    {
        Menu::create($request->filldata());
        flash('创建成功', 'success');

        return back();
    }

    public function edit(Menu $administratorMenu, $id)
    {
        $permissions = Permission::get();
        $menus = $administratorMenu->menus();
        $menu = Menu::findOrFail($id);

        return view('backend.menu.edit', compact('menus', 'menu', 'permissions'));
    }

    public function update(MenuRequest $request, $id)
    {
        $menu = Menu::findOrFail($id);
        $menu->fill($request->filldata())->save();
        flash('编辑成功', 'success');

        return back();
    }

    public function destroy($id)
    {
        $menu = Menu::findOrFail($id);
        //该分类下是否有子分类
        $exists = Menu::whereParentId($menu->id)->exists();
        if ($exists){
            flash('该分类下还有子分类,请删除子分类后再删除该分类', 'error');

            return back();
        }
        $menu->delete();
        flash('删除成功', 'success');

        return back();
    }


}
